package com.crrcdt.vue_project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crrcdt.vue_project.entity.Manager;
import com.crrcdt.vue_project.entity.User;
import com.crrcdt.vue_project.result.Result;
import com.crrcdt.vue_project.result.ResultFactory;
import com.crrcdt.vue_project.service.ManagerService;
import com.crrcdt.vue_project.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author lj on 2020/10/21.
 * @version 1.0
 */
@RestController
@RequestMapping(value = "/api/private/v1")
@Slf4j
public class LoginController {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ManagerService managerService;
    @PostMapping("/login")
    public Result loginManager(@RequestBody User user) {
        final ValueOperations ops = redisTemplate.opsForValue();
        String index_code = (String) ops.get("index_code");
        if(!user.getCheckcode().equalsIgnoreCase(index_code)){
            return ResultFactory.buildFailResult("登录失败");
        }
        SimpleHash simpleHash = new SimpleHash("MD5", user.getPassword(), user.getUsername(), 1024);
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), simpleHash.toString());
        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        try {
            //完成登录 这里会跳到MyRealm doGetAuthenticationInfo 进行认证
            subject.login(token);
            //获得用户对象
            Manager resultUser = (Manager) subject.getPrincipal();
            HashMap<Object, Object> data = new HashMap<>();
            data.put("id", resultUser.getMgId());
            data.put("rid", resultUser.getRoleId());
            data.put("username", resultUser.getMgName());
            data.put("mobile", resultUser.getMgMobile());
            data.put("email", resultUser.getMgEmail());
            //生成token返回给客户端
            data.put("token", JWTUtil.sign(resultUser));
            return ResultFactory.buildSuccessResult(data, "登录成功");
        } catch (AuthenticationException e) {
            //登录失败
            return ResultFactory.buildFailResult("登录失败");
        }
    }
    @PostMapping("/register")
    public Result registerManager(@RequestBody User user) {
        final Manager manager = new Manager();
        manager.setMgName(user.getUsername());
        // 进行加密
        final String saltPwd = saltPwd(user.getPassword(), user.getUsername());
        manager.setMgPwd(saltPwd);
        Long time = System.currentTimeMillis();
        manager.setMgTime(time);
        final boolean res = managerService.save(manager);
        if(res){
            return ResultFactory.buildSuccessResult(manager,"注册成功！");
        }
        return ResultFactory.buildFailResult("注册失败");
        }
    // 盐值加密
    public String saltPwd(String pwd,String userName){
//        明码
        String password = pwd;
        //加密算法
        String algorithmName = "MD5";
        //要加密的密码
        Object source = password;
        //盐值，一般都是用户名或者userid，要保证唯一
        Object salt =userName;
        //加密次数
        int hashIterations = 1024;
//      String algorithmName, Object source, Object salt, int hashIterations
        SimpleHash simpleHash = new SimpleHash(algorithmName,source,salt,hashIterations);
        //打印出经过盐值、加密次数、md5后的密码
        System.out.println(simpleHash.toString());
        return simpleHash.toString();
    }
//   public static void main(String[] args) {
//        //明码
//        String password = "123456";
//        //加密算法
//        String algorithmName = "MD5";
//        //要加密的密码
//        Object source = password;
//        //盐值，一般都是用户名或者userid，要保证唯一
//        Object salt = "admin";
//        //加密次数
//        int hashIterations = 1024;
////      String algorithmName, Object source, Object salt, int hashIterations
//        SimpleHash simpleHash = new SimpleHash(algorithmName,source,salt,hashIterations);
//        //打印出经过盐值、加密次数、md5后的密码
//        System.out.println(simpleHash.toString());
//    }
}
